using System.Linq;
using StackCalc.Instructions;

namespace StackCalc.Parsing.ParsingUnits
{
	public class IntegerParser : BaseParsingUnit<PushInteger>
	{
		protected override bool CanParseImplementation(string input)
		{
			// has to start with a digit
			return char.IsDigit(input[0]);
		}

		protected override bool HasSyntaxErrorImplementation(string input)
		{
			// take maximum consecutive amount of digits
			string relevantInput = new string(input.TakeWhile(c => char.IsDigit(c)).ToArray());

			int result;
			return !int.TryParse(relevantInput, out result);
		}

		public override string GetErrorDescription()
		{
			return "Integer out of 32Bit range!";
		}

		protected override PushInteger ParseImplementation(string input)
		{
			// take maximum consecutive amount of digits
			string relevantInput = new string(input.TakeWhile(c => char.IsDigit(c)).ToArray());
			return new PushInteger(int.Parse(relevantInput));
		}

		protected override string TrunkateImplementation(string input)
		{
			// skip maximum consecutive amount of digits
			return new string(input.SkipWhile(c => char.IsDigit(c)).ToArray());
		}
	}
}
